package com.lanyanhua.job.service.impl;

import com.lanyanhua.job.dao.JobGroupRepository;
import com.lanyanhua.job.entity.JobGroup;
import com.lanyanhua.job.entity.Page;
import com.lanyanhua.job.service.IJobGroupService;
import com.lanyanhua.job.service.base.impl.MyServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: lanyanhua
 * @Date: 2018/11/1 0001 09:58
 * @Description:
 */
@Slf4j
@Service
public class JobGroupServiceImpl extends MyServiceImpl<JobGroup, String> implements IJobGroupService {

    private JobGroupRepository groupRepository;

    @Autowired
    public JobGroupServiceImpl(JobGroupRepository groupRepository) {
        super(groupRepository);
        this.groupRepository = groupRepository;
    }

    @Override
    public Page findJobGroupPage(JobGroup jobGroup, int page, Integer limit) {
        return new Page(
                groupRepository.findAll((Root<JobGroup> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                    List<Predicate> predicates = new ArrayList<>();
                    if (!StringUtils.isEmpty(jobGroup.getGroupName())) {
                        predicates.add(cb.like(root.get("groupName").as(String.class), "%" + jobGroup.getGroupName() + "%"));
                    }
                    if (!StringUtils.isEmpty(jobGroup.getGroupNo())) {
                        predicates.add(cb.like(root.get("groupNo").as(String.class), "%" + jobGroup.getGroupNo() + "%"));
                    }
                    return query.where(predicates.toArray(new Predicate[0])).getRestriction();
                }, PageRequest.of(page, limit))
        );
    }
}
